package com.achilles.activity;

import android.animation.ArgbEvaluator;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.res.ColorStateList;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;

import com.achilles.bean.DataBean;
import com.achilles.bean.GiftBean;
import com.achilles.bean.ProjectBean;
import com.achilles.callback.IListFragmentChanged;
import com.achilles.database.DBManager;
import com.achilles.fragment.BaseFragment;
import com.achilles.fragment.BaseListFragment;
import com.achilles.fragment.GiftFragment;
import com.achilles.fragment.HistoryFragment;
import com.achilles.fragment.ProjectFragment;
import com.achilles.fragment.ScoreFragment;
import com.achilles.fragment.SettingFragment;
import com.achilles.playtask.R;
import com.achilles.utils.AlarmUtils;
import com.achilles.utils.DisplayUtils;
import com.achilles.widget.CreateGiftView;
import com.achilles.widget.CreateProjectView;
import com.achilles.widget.DialogView;
import com.achilles.widget.TaskFloatingActionButton;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends ToolBarActivity implements View.OnClickListener {

    public static final int INIT_FRAGMENT_ITEM = 0;
    private BaseListFragment mProjectFragment, mGiftFragment;
    private TaskFloatingActionButton mFabAddProjectOrGift;
    private FragmentType mCurrentFragmentType;
    private AlertDialog mProjectDialog, mGiftDialog;
    private DialogView createProjectView,createGiftView;
    private ViewPager mViewPager;
    private IListFragmentChanged mIListFragmentChanged;

    private List<Drawable> mBottomDrawableList = new ArrayList<>();
    private List<ImageView> mBottomImageViewList = new ArrayList<>();
    private List<Fragment> mFragmentList = new ArrayList<>();

    private ArgbEvaluator mArgbEvaluator = new ArgbEvaluator();
    private int mBottomColorSelect;
    private int mBottomColorUnSelect;

    public enum FragmentType {
        ProjectFragment, GiftFragment, ScoreFragment, HistoryFragment,SettingFragment
    }

    @Override
    protected void init() {
        super.init();
        initInterface();
        initView();
        initDialog();
        initBottomDrawable();
        initViewPager();
        updateLoginTime();
        setAlarm();
    }

    private void setAlarm() {
        if (AlarmUtils.isAlarmEnable(this)) {
            int hour = AlarmUtils.getLocalAlarmHour(this);
            int minute = AlarmUtils.getLocalAlarmMinute(this);
            AlarmUtils.setAlarm(this,hour,minute);
        }
    }

    private void initViewPager() {
        mCurrentFragmentType = FragmentType.ProjectFragment;

        mProjectFragment = ProjectFragment.getInstance(mIListFragmentChanged);
        mGiftFragment = GiftFragment.getInstance(mIListFragmentChanged);
        BaseFragment mScoreFragment = ScoreFragment.getInstance();
        BaseFragment mHistoryFragment = HistoryFragment.getInstance();
        Fragment mSettingFragment = SettingFragment.getInstance();

        mFragmentList.add(mProjectFragment);
        mFragmentList.add(mGiftFragment);
        mFragmentList.add(mScoreFragment);
        mFragmentList.add(mHistoryFragment);
        mFragmentList.add(mSettingFragment);

        mViewPager = (ViewPager) findViewById(R.id.viewPager);
        mViewPager.setAdapter(new ViewPagerAdapter(getFragmentManager(),mFragmentList));
        mViewPager.setOffscreenPageLimit(mFragmentList.size() - 1);
        mViewPager.setCurrentItem(INIT_FRAGMENT_ITEM);
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            final int DELAY_TIME = 100;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                changeBottomIconColor(position,positionOffset);
            }

            @Override
            public void onPageSelected(final int position) {
                mCurrentFragmentType = FragmentType.values()[position];
                changeFragment();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setBottomIconSelected(position);
                    }
                },DELAY_TIME); //设置延时以便消除残影（如：从点击底部按钮切换时，可能出现残影）
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        setBottomIconSelected(INIT_FRAGMENT_ITEM);
        changeFragment();
    }

    /*控制底部图标的渐变色*/
    private void changeBottomIconColor(int position, float positionOffset) {
        Log.d("changeBottomIconColor","position: " + position + " positionOffset: " + positionOffset);
        ImageView imageViewStart, imageViewEnd = null;
        Drawable drawableStart, drawableEnd = null, drawableColorStart, drawableColorEnd;

        imageViewStart = mBottomImageViewList.get(position);
        drawableStart = mBottomDrawableList.get(position);

        if (position != mBottomDrawableList.size() - 1) {
            imageViewEnd = mBottomImageViewList.get(position + 1);
            drawableEnd = mBottomDrawableList.get(position + 1);
        } else {
            imageViewEnd = null;
            drawableEnd = null;
        }

        if (imageViewStart != null) {
            int colorStart = (int) mArgbEvaluator.evaluate(positionOffset, mBottomColorSelect, mBottomColorUnSelect);
            drawableColorStart = DisplayUtils.tintDrawable(drawableStart, ColorStateList.valueOf(colorStart));
            imageViewStart.setImageDrawable(drawableColorStart);
        }
        if (imageViewEnd != null) {
            int colorStart = (int) mArgbEvaluator.evaluate(positionOffset, mBottomColorUnSelect, mBottomColorSelect);
            drawableColorEnd = DisplayUtils.tintDrawable(drawableEnd, ColorStateList.valueOf(colorStart));
            imageViewEnd.setImageDrawable(drawableColorEnd);
        }
    }

    private void changeFragment() {
        if (mCurrentFragmentType == FragmentType.GiftFragment) {
            mFabAddProjectOrGift.scaleIn();
            mFabAddProjectOrGift.setImageResource(R.drawable.ic_add);
        } else if (mCurrentFragmentType == FragmentType.ProjectFragment) {
            mFabAddProjectOrGift.scaleIn();
        } else {
            mFabAddProjectOrGift.scaleOut();
        }
        setTitleName(mCurrentFragmentType.ordinal());
    }

    private void initBottomDrawable() {
        mBottomColorSelect = ContextCompat.getColor(this, R.color.colorPrimary);
        mBottomColorUnSelect = ContextCompat.getColor(this, R.color.gray);

        Drawable mProjectDrawable = ContextCompat.getDrawable(this, R.drawable.ic_library_books).mutate();
        Drawable mGiftDrawable = ContextCompat.getDrawable(this, R.drawable.ic_card_giftcard).mutate();
        Drawable mScoreDrawable = ContextCompat.getDrawable(this, R.drawable.ic_monetization_on).mutate();
        Drawable mHistoryDrawable = ContextCompat.getDrawable(this, R.drawable.ic_date_range).mutate();
        Drawable mSettingDrawable = ContextCompat.getDrawable(this, R.drawable.ic_settings).mutate();

        mBottomDrawableList.add(mProjectDrawable);
        mBottomDrawableList.add(mGiftDrawable);
        mBottomDrawableList.add(mScoreDrawable);
        mBottomDrawableList.add(mHistoryDrawable);
        mBottomDrawableList.add(mSettingDrawable);

    }

    private void setBottomIconSelected(int index) {

        for (int i = 0; i < mBottomImageViewList.size(); i++) {
            ImageView imageView = mBottomImageViewList.get(i);
            Drawable drawable = mBottomDrawableList.get(i);
            if (i == index) {
                Drawable imageDrawableSelect = DisplayUtils.tintDrawable(drawable, ColorStateList.valueOf(mBottomColorSelect));
                imageView.setImageDrawable(imageDrawableSelect);
            } else {
                Drawable imageDrawableUnSelect = DisplayUtils.tintDrawable(drawable, ColorStateList.valueOf(mBottomColorUnSelect));
                imageView.setImageDrawable(imageDrawableUnSelect);
            }
        }
    }

    private void updateLoginTime() {
        int loginTime = DBManager.getInstance().getAppLoginTimes();
        DBManager.getInstance().insertOrUpdateLoginTime(loginTime + 1);
    }

    private void initInterface() {
        mIListFragmentChanged = new IListFragmentChanged() {
            @Override
            public void onListScrollDirectionChanged(boolean isScrollUp) {
                Log.d("onListScrollDirection","isScrollUp "+isScrollUp);
                if (isScrollUp) {
                    mFabAddProjectOrGift.moveOut();
                } else {
                    mFabAddProjectOrGift.moveIn();
                }
            }

            @Override
            public void onHasItemSelected(boolean hasSelected) {
                if (hasSelected) {
                    mFabAddProjectOrGift.moveIn();
                }
                Log.d("AchillesL","onHasItemSelected: " + hasSelected);
                mFabAddProjectOrGift.setImageResource(hasSelected ? R.drawable.ic_done : R
                        .drawable.ic_add);
            }

            @Override
            public void onCreateViewEdit(FragmentType fragmentType, DataBean dataBean) {
                if (fragmentType == FragmentType.ProjectFragment) {
                    createProjectView.editData(dataBean);
                    showProjectDialog();
                } else if (fragmentType == FragmentType.GiftFragment) {
                    createGiftView.editData(dataBean);
                    showGiftDialog();
                }
            }
        };
    }

    private void showGiftDialog() {
        mGiftDialog.show();
        mGiftDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new DialogClick
                (FragmentType.GiftFragment, createGiftView));
    }

    private void updateProjectList() {
        mProjectFragment.updateList();
    }

    private void updateGiftList() {
        mGiftFragment.updateList();
    }

    protected void initView() {
        mFabAddProjectOrGift = (TaskFloatingActionButton) findViewById(R.id.fabAddProjectOrGift);
        mFabAddProjectOrGift.setOnClickListener(this);

        ImageView mIvProject = (ImageView) findViewById(R.id.ivProject);
        ImageView mIvGift = (ImageView) findViewById(R.id.ivGift);
        ImageView mIvScore = (ImageView) findViewById(R.id.ivScoreInfo);
        ImageView mIvHistory = (ImageView) findViewById(R.id.ivHistory);
        ImageView mIvSetting = (ImageView) findViewById(R.id.ivSetting);

        mBottomImageViewList.add(mIvProject);
        mBottomImageViewList.add(mIvGift);
        mBottomImageViewList.add(mIvScore);
        mBottomImageViewList.add(mIvHistory);
        mBottomImageViewList.add(mIvSetting);

        for (ImageView imageView : mBottomImageViewList) {
            imageView.setOnClickListener(this);
        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_main;
    }

    private void initDialog() {
        createProjectView = new CreateProjectView(this);
        createGiftView = new CreateGiftView(this);

        AlertDialog.Builder projectDialogBuilder = new AlertDialog.Builder(this);
        projectDialogBuilder.setTitle(R.string.projectDialogTitle);
        projectDialogBuilder.setNegativeButton(android.R.string.cancel, null);
        projectDialogBuilder.setPositiveButton(android.R.string.ok, null);
        projectDialogBuilder.setOnDismissListener(new DialogDismiss(createProjectView));
        projectDialogBuilder.setCancelable(false);
        projectDialogBuilder.setView(createProjectView.getView());
        mProjectDialog = projectDialogBuilder.create();
        mProjectDialog.setOnKeyListener(new DialogKeyClick());

        AlertDialog.Builder giftDialogBuilder = new AlertDialog.Builder(this);
        giftDialogBuilder.setTitle(R.string.giftDialogTitle);
        giftDialogBuilder.setPositiveButton(android.R.string.ok, null);
        giftDialogBuilder.setNegativeButton(android.R.string.cancel, null);
        giftDialogBuilder.setCancelable(false);
        giftDialogBuilder.setOnDismissListener(new DialogDismiss(createGiftView));
        giftDialogBuilder.setView(createGiftView.getView());
        mGiftDialog = giftDialogBuilder.create();
        mGiftDialog.setOnKeyListener(new DialogKeyClick());
    }

    class DialogDismiss implements DialogInterface.OnDismissListener {
        private final DialogView dialogView;

        public DialogDismiss(DialogView dialogView) {
            this.dialogView = dialogView;
        }

        @Override
        public void onDismiss(DialogInterface dialog) {
            dialogView.reset();
        }
    }

    class DialogClick implements View.OnClickListener {
        private final FragmentType fragmentType;
        private final DialogView dialogView;

        public DialogClick(FragmentType fragmentType, DialogView dialogView) {
            this.fragmentType = fragmentType;
            this.dialogView = dialogView;
        }

        @Override
        public void onClick(View v) {
            if (!dialogView.isParamValid()) {
                return;
            }
            switch (fragmentType) {
                case ProjectFragment: {
                    DBManager.getInstance().insertOrUpdateProjectData((ProjectBean) dialogView
                            .getData());
                    updateProjectList();
                    break;
                }
                case GiftFragment: {
                    DBManager.getInstance().insertOrUpdateGiftData((GiftBean) dialogView.getData());
                    updateGiftList();
                    break;
                }
                default:
                    break;
            }
            mProjectDialog.dismiss();
            mGiftDialog.dismiss();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivProject: {
                mViewPager.setCurrentItem(0);
                break;
            }
            case R.id.ivGift: {
                mViewPager.setCurrentItem(1);
                break;
            }
            case R.id.ivScoreInfo: {
                mViewPager.setCurrentItem(2);
                break;
            }
            case R.id.ivHistory:{
                mViewPager.setCurrentItem(3);
                break;
            }
            case R.id.ivSetting:{
                mViewPager.setCurrentItem(4);
                break;
            }
            case R.id.fabAddProjectOrGift: {
                addProjectOrGift();
                break;
            }
            default:
                break;
        }
    }



    private void addProjectOrGift() {
        switch (mCurrentFragmentType) {
            case ProjectFragment: {
                List<DataBean> completeProject = ((ProjectFragment)mProjectFragment).getSelectProjectList();
                if (completeProject.isEmpty()) {
                    addProject();
                }else {
                    saveCompleteProject(completeProject);
                }
                break;
            }
            case GiftFragment: {
                addGift();
                break;
            }
            default:
                break;
        }
    }

    private void saveCompleteProject(List<DataBean> completeProject) {
        ((ProjectFragment)mProjectFragment).saveCompleteProject(completeProject,true,true);
    }

    private void addGift() {
        showGiftDialog();
    }

    private void addProject() {
        showProjectDialog();
    }

    private void showProjectDialog() {
        mProjectDialog.show();
        mProjectDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new DialogClick
                (FragmentType.ProjectFragment, createProjectView));
    }

    private class DialogKeyClick implements DialogInterface.OnKeyListener {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            Log.d("onKeyDown","keyCode: " + keyCode + "KeyEvent: " + event.toString());
            switch (keyCode) {
                case KeyEvent.KEYCODE_BACK:{
                    if (mProjectDialog.isShowing()) {
                        mProjectDialog.dismiss();
                    } else if (mGiftDialog.isShowing()) {
                        mGiftDialog.dismiss();
                    }
                    return true;
                }
                case KeyEvent.KEYCODE_ENTER:{
                    Log.d("onKeyDown","mProjectDialog.isShowing(): " + mProjectDialog.isShowing());
                    if (mProjectDialog.isShowing()) {
                        return createProjectView.onKeyDown(keyCode,event);
                    } else if (mGiftDialog.isShowing()) {
                        return createGiftView.onKeyDown(keyCode,event);
                    }
                }
            }
            return false;
        }
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;

        public ViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList) {
            super(fm);
            this.fragmentList = fragmentList;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }
    }
}
